package project.order.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kernel.util.Arith;
import kernel.util.StringUtils;
import kernel.web.BaseAction;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import project.order.Order;
import project.order.OrderService;
import project.order.OrderTemp;
import project.order.OrderTempService;
import project.order.weixi.CommonUtil;
import project.order.weixi.SDKRuntimeException;
import project.order.weixi.WxPayHelper;
import project.order.work.WxOpenIdHelper;
import project.product.Brand;
import project.product.BrandService;
import project.product.Cloth;
import project.product.ClothService;
import project.user.User;
import project.user.UserService;
import project.vip.po.Vip;
import project.vip.services.AdminVipService;
import project.vip.utils.KBProperties;
import project.vip.utils.VipWxOpenIdHelper;

public class OrderSingleAction extends BaseAction {

	/**
	 * Member Description
	 */

	private static final long serialVersionUID = 812538998403473688L;
	private AdminVipService adminVipService;
	/**
	 * Member Description
	 */
	private Cloth cloth;
	private String brand_id;
	private String cloth_id;
	private Brand brand;

	private BrandService brandService;

	private OrderService orderService;

	private ClothService clothService;
	// 用户姓名
	private String name;
	private String fd4sm;
	private String fd4cs;
	// 手机号码
	private String phone;

	// 收货地址
	private String address;

	private String bizPackage;

	private String state;

	private String code;

	private String openid;

	private boolean binding;

	private UserService userService;

	private OrderTempService orderTempService;

	private Brand brandVip = null;
	/**
	 * 成功下单后的order id
	 */
	private String fdOrderId;
	public String view() {

		OrderTemp orderTemp = orderTempService.get(state);
		brand_id = orderTemp.getBrand();
		brandVip = brandService.getBrand(brand_id);
		if (KBProperties.isTest) {
			openid = WxOpenIdHelper.getOpenId(code);
		}

		cloth_id = orderTemp.getCloth();
		User userInfo = userService.find(openid);
		if (userInfo != null) {
			name = userInfo.getName();
			phone = userInfo.getPhone();
			address = userInfo.getAddress();
		}

		return "view";
	}
	/**
	 * 更新order
	 * @return
	 * @throws SDKRuntimeException
	 */
	public String updateOrder() throws SDKRuntimeException {

		HashMap<String, String> nativeObj = new HashMap<String, String>();
		Order o = orderService.getOrder(fdOrderId);
		o.setPayment(1);
        o.setFirmOrder("1");
		orderService.update(o);

		Vip vip = adminVipService.find(openid);
		System.out.println("--vip"+openid);
		if (vip != null) {
			
			if(vip.getGoldBt() > 0){
				vip.setGoldBt(vip.getGoldBt() - o.getFd4goldnum());//扣减金纽扣
				//判断是否选择上门券
				if(o.getFd4sm().equals("10")){//需要上门券
					vip.setSmTicket(vip.getSmTicket() - 1);
				}
				//判断是否选择衬衫券
				if(o.getFd4cs().equals("10")){
					vip.setCsTicket(vip.getCsTicket() - 1);
				}
				//判断单品是否是上门券，如果是就要增加上门券
				brandVip = brandService.getBrand(o.getButton());
				if(null != brandVip && brandVip.getFdType().equals("20")){//上门券
					vip.setSmTicket(vip.getSmTicket() + 1);
				}

				System.out.println("--vip"+vip.getGoldBt()+"--"+vip.getSmTicket() +"--"+vip.getCsTicket());
				adminVipService.update(vip);
				nativeObj.put("code", "success");
				nativeObj.put("message", "下单成功!");
			}else{
				nativeObj.put("code", "fail");
				nativeObj.put("message", "金纽扣不足!");
			}
		}else{
			nativeObj.put("code", "fail");
			nativeObj.put("message", "vip查找失败!");
		}
		
		
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.println(JSONObject.fromObject(nativeObj).toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}
	/**
	 * check order
	 * 符合条件：是会员，有金纽扣,单品不用上门券
	 * @return
	 * @throws SDKRuntimeException
	 */
	public String checkOrder() throws SDKRuntimeException {

		HashMap<String, String> nativeObj = new HashMap<String, String>();
		
		Vip vip = adminVipService.find(openid);
		if (vip != null) {
			if(vip.getGoldBt() > 0){//有金纽扣
				//判断是否选择上门券
				if(null != fd4sm && fd4sm.equals("10")){//需要上门券
					if(vip.getInvNum() > 0){//有足够的上门券
						
					}else{
						nativeObj.put("code", "fail");
						nativeObj.put("message", "上门券不足!");
					}
				}
				
				nativeObj.put("code", "success");
				nativeObj.put("message", "可以下单!");
			}else{
				nativeObj.put("code", "fail");
				nativeObj.put("message", "金纽扣不足!");
			}
		}else{
			nativeObj.put("code", "fail");
			nativeObj.put("message", "找不到该vip!");
		}
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.println(JSONObject.fromObject(nativeObj).toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	public String pay() throws SDKRuntimeException {

		

			User user = userService.find(openid);
			if (user != null) {
				user.setAddress(address);
				user.setName(name);
				user.setPhone(phone);
				userService.update(user);
			} else {
				user = new User();
				user.setAddress(address);
				user.setName(name);
				user.setPhone(phone);
				user.setOpenId(openid);
				userService.save(user);
			}
			Order order = new Order();
			getBrand();
			getCloth();
			//判断
			String message = "";
			String code = "success";
			
			Vip vip = adminVipService.find(openid);
			if (vip != null) {
				if(vip.getGoldBt() - brand.getFd4goldnum() >= 0){//有金纽扣
					//vip.setGoldBt(vip.getGoldBt() - brand.getFd4goldnum());//扣减金纽扣
					order.setFd4goldnum(brand.getFd4goldnum());//订单消耗金纽扣
					//判断是否选择上门券
					if(null != fd4sm && fd4sm.equals("true")){//需要上门券
						if(vip.getSmTicket() > 0){//有足够的上门券
							//vip.setSmTicket(vip.getSmTicket() - 1);
							order.setFd4sm("10");//订单消耗上门券
						}else{
							//code = "fail";
							//message = "上门券不足!";
							order.setFd4sm("00");//无上门券
						}
					}else{
						order.setFd4sm("00");//订单消耗上门券
					}
					//判断是否选择衬衫券
					if(null != fd4cs && fd4cs.equals("true")){//需要上门券
						if(vip.getCsTicket() > 0){
							//vip.setCsTicket(vip.getCsTicket() - 1);
							order.setPrice(brand.getBookPrice() - brand.getFdTypePrice());
							message = "系统自动使用衬衫券["+brand.getFdTypePrice()+"]抵扣!";
							order.setFd4cs("10");//订单消耗衬衫券
						}else{
							//code = "fail";
							//message = "衬衫券不足!";
							order.setFd4sm("00");//无上门券
						}
					}else{
						order.setFd4cs("00");//订单消耗衬衫券
						order.setPrice(brand.getBookPrice());
					}
					
				}else{
					code = "fail";
					message = "金纽扣不足!";
				}
			}else{
				code = "fail";
				message = "你不是会员!";
			}
			
		if(code.equals("fail")){
			HashMap<String, String> tempMap = new HashMap<String, String>();
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out;
			try {
				tempMap.put("code", code);
				tempMap.put("message", message);
				out = response.getWriter();
				out.println(JSONObject.fromObject(tempMap).toString());
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}else{
			order.setName(name);
			order.setAddress(address);
			order.setPhone(phone);

			order.setButton(brand.getId().toString());
			order.setPrice(brand.getBookPrice());
			order.setBrand(brand.getName());
			order.setBrand_img(brand.getImg());
			order.setSingle(brand.getSingle());
			order.setOpenId(openid);
			
			order.setCloth(cloth.getName());
			order.setCloth_img(cloth.getImg());

			order.setFd4gold("10");//设置金纽扣不使用
			order.setFd4goldnum(1);//设置金纽扣数量0 为了区别是购买的卡会员而不是购买商城的商品
			order.setPayment(0);

	        order.setFirmOrder("0");
			orderService.save(order);
			
			WxPayHelper wxPayHelper = new WxPayHelper();

			/**
			 * 商品描述
			 */
			wxPayHelper.SetParameter("body", "" + message+order.toString());

			/**
			 * 订单号
			 */
			wxPayHelper.SetParameter("out_trade_no", order.getId().toString());
			/**
			 * 付款金额
			 */
			// wxPayHelper.SetParameter("total_fee", String.valueOf(1));
			wxPayHelper.SetParameter(
					"total_fee",
					String.valueOf(Arith.mul(order.getPrice(), 100)).substring(
							0,
							String.valueOf(Arith.mul(order.getPrice(), 100))
									.indexOf(".")));
			HttpServletRequest req = (HttpServletRequest) ServletActionContext
					.getRequest();
			String visitorIp = req.getRemoteAddr();
			wxPayHelper.SetParameter("spbill_create_ip", visitorIp);
			wxPayHelper.SetParameter("openid", openid);

			HashMap<String, String> tempMap = new HashMap<String, String>();
			tempMap = wxPayHelper.CreateBizPackageMap();
			//增加订单号回传
			tempMap.put("fdOrderId", order.getId().toString());
			tempMap.put("code", code);
			tempMap.put("message", message);
			
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out;
			try {
				out = response.getWriter();
				out.println(JSONObject.fromObject(tempMap).toString());
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
		

	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Brand getBrand() {
		if (brand == null) {
			brand = brandService.getBrand(brand_id);
		}

		return brand;
	}

	public void setBrandService(BrandService brandService) {
		this.brandService = brandService;
	}

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	public String getBrand_id() {
		return brand_id;
	}

	public void setBrand_id(String brand_id) {
		this.brand_id = brand_id;
	}

	public String getBizPackage() {
		return bizPackage;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getOpenid() {
		return openid;
	}

	public void setOpenid(String openid) {
		this.openid = openid;
	}

	public boolean isBinding() {
		return binding;
	}

	public void setBinding(boolean binding) {
		this.binding = binding;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setOrderTempService(OrderTempService orderTempService) {
		this.orderTempService = orderTempService;
	}

	public Cloth getCloth() {
		if (cloth == null) {
			// System.out.println("clothService="+clothService);
			cloth = clothService.getCloth(cloth_id);
		}
		return cloth;
	}

	public void setClothService(ClothService clothService) {
		this.clothService = clothService;
	}

	public String getCloth_id() {
		return cloth_id;
	}

	public void setCloth_id(String cloth_id) {
		this.cloth_id = cloth_id;
	}

	/**
	 * @return the fd4sm
	 */
	public String getFd4sm() {
		return fd4sm;
	}

	/**
	 * @param fd4sm
	 *            the fd4sm to set
	 */
	public void setFd4sm(String fd4sm) {
		this.fd4sm = fd4sm;
	}

	/**
	 * @return the fdOrderId
	 */
	public String getFdOrderId() {
		return fdOrderId;
	}

	/**
	 * @param fdOrderId the fdOrderId to set
	 */
	public void setFdOrderId(String fdOrderId) {
		this.fdOrderId = fdOrderId;
	}

	/**
	 * @param adminVipService the adminVipService to set
	 */
	public void setAdminVipService(AdminVipService adminVipService) {
		this.adminVipService = adminVipService;
	}
	/**
	 * @return the brandVip
	 */
	public Brand getBrandVip() {
		return brandVip;
	}
	/**
	 * @param brandVip the brandVip to set
	 */
	public void setBrandVip(Brand brandVip) {
		this.brandVip = brandVip;
	}
	/**
	 * @return the fd4cs
	 */
	public String getFd4cs() {
		return fd4cs;
	}
	/**
	 * @param fd4cs the fd4cs to set
	 */
	public void setFd4cs(String fd4cs) {
		this.fd4cs = fd4cs;
	}

}
